/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/store/';
import router from '@/router/'
import {serialize,getCookie,expireLogin} from '@/util/util'
import {getToken} from '@/util/auth'
import {Message} from 'element-ui'
import website from '@/config/website';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {Base64} from 'js-base64';

if (getCookie('mYToken')) {
  store.commit('SET_TOKEN', getCookie('mYToken'));
}
axios.defaults.timeout = 300000;

//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
  showSpinner: false
});
axios.interceptors.request.use(config => {
  NProgress.start()
  //判断是否存在token
  const path = router.currentRoute.path;
  if (!getToken() && path != '/login' && path != '/') {
    expireLogin();
    return Promise.reject({})
  }
  const meta = (config.meta || {});
  const isToken = meta.isToken === false;
  config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
  sessionStorage.setItem("upAuthorization", `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`)
  if (getToken() && !isToken) {
    config.headers['Blade-Auth'] = 'bearer ' + getToken()
  }
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }

  return config
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
  NProgress.done();
  //特殊状态码 - /api/blade-data/select/show
  if (res.status == 503) {
    expireLogin();
    return Promise.reject(res);
  }

  //如下:成功情况
  let status = res.data.code || 200;//登录接口单独处理默认给200
  const message = res.data.msg;
  switch (status) {
    case 200:
      return res;
    case 401://按钮未授权，token过期
      expireLogin();
      return Promise.reject(res);
    case 500:
      return Promise.reject(res);
    case 404:
      return Promise.reject(res);
    case 400://业务错误 - 正常报错
      const API= res['config']['url'];
      if(API =='/api/blade-product/product/import'||API=='/api/blade-email/smtp'){//产品导入
        return Promise.resolve(res);
      }else{
        Message({
          showClose: true,
          message: message,
          type: 'success',
          duration: 1500
        })
        return Promise.reject(res);
      }
    default:
      return Promise.reject(res.data);
  }
}, error => {
  NProgress.done();
  let URL = '';
  if (JSON.stringify(error) != '{}') {
    URL = error['config']['url'];
  }
  if (URL.indexOf('/api/blade-data/select/show?Blade-Auth=') != -1
    || URL.indexOf('/api/blade-data/select/DataServlet') != -1) {//特殊
    return Promise.resolve({});
  }
  return Promise.reject(new Error(error));
})

export default axios;
